/**
 * 
 */
package pt.mleiria.bean;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.codec.binary.Base64;

/**
 * @author NB13712
 *
 */
@Stateless
public class CryptoBean implements ICryptoBean{

	@PersistenceContext(unitName = "pu1")
	private EntityManager em;
	
	@EJB
	private IClientBean clientBean;
	
	public CryptoBean() {
	}

	public String encryptText(final String name, final int key_id, final String plainText) 
			throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, 
			IllegalBlockSizeException, BadPaddingException {
		
		// Get a cipher object.
		final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		SecretKey key = getKey(name, key_id);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		final byte[] stringBytes = plainText.getBytes("UTF8");
		final byte[] raw = cipher.doFinal(stringBytes);
		//System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation());
		return Base64.encodeBase64String(raw);
	}
	
	public String decryptText(String name, int key_id, String cipherText) 
			throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, 
			BadPaddingException, UnsupportedEncodingException{
		
		// Get a cipher object.
		final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		SecretKey key = getKey(name, key_id);
		cipher.init(Cipher.DECRYPT_MODE, key);
		
		byte[] raw = Base64.decodeBase64(cipherText);
		byte[] stringBytes = cipher.doFinal(raw);
		return new String(stringBytes, "UTF8");
	}
	
	private SecretKey getKey(final String name, final int key_id){
		final byte[] bKey = clientBean.getKey(name, key_id);
		final SecretKey key = new SecretKeySpec(bKey, 0, 8, "DES");
		return key;
	}
	
	

}
